<template>
  <div class="song-lyric">
    <h1 class="lyric-title">歌词</h1>
    <!-- 有歌词 -->
    <ul class="has-lyric" v-if="lyric.length" key="index">
      <li v-for="(item,index) in lyric" :key="index">
        {{item[1]}}
      </li>
    </ul>
    <!-- 没有歌词 -->
    <div v-else class="no-lyric" key="no-lyric">
      <span>暂无歌词</span>
    </div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
export default {
  name: "SongInfo",
  data(){
    return{
      lyric:[],
      curTime:0
    }
  },
  methods:{
    //解析歌词
    parseLyric(text){
      let lines = text.split("\n");                   //将歌词按行分解成数组
      let pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g; //时间格式的正则表达式
      let result = [];                                //返回值
      //对于歌词格式不对的直接返回
      if(!(/\[.+\]/.test(text))){
        return [[0,text]]
      }
      //去掉前面格式不正确的行
      while(!pattern.test(lines[0])){
        lines = lines.slice(1);
      }
      //遍历每一行，形成一个每行带着俩元素的数组，第一个元素是以秒为计算单位的时间，第二个元素是歌词
      for(let item of lines){
        let time = item.match(pattern);  //存前面的时间段
        let value = item.replace(pattern,'');//存后面的歌词
        for(let item1 of time){
          let t = item1.slice(1,-1).split(":");   //取出时间，换算成数组
          if(value!=''){
            result.push([parseInt(t[0],10)*60 + parseFloat(t[1]),value]);
          }
        }
      }
      //按照第一个元素--时间--排序
      result.sort(function(a,b){
        return a[0] - b[0];
      });
      return result;
    },
  },
  mounted() {
    this.lyric=this.parseLyric(this.oldLyric)
    this.$bus.$on('curTime',(curTime)=>{
      this.curTime=curTime
    })
  },
  watch:{
    curTime(){
      if(this.lyric.length>0){
        for(let i=0;i<this.lyric.length;i++){
          if(this.curTime>=this.lyric[i][0]){
            for(let j=0;j<this.lyric.length;j++){
              document.querySelectorAll('.has-lyric li')[j].style.color = '#000';
              document.querySelectorAll('.has-lyric li')[j].style.fontSize = '15px';
            }
            if(i>=0){
              document.querySelectorAll('.has-lyric li')[i].style.color = '#95d2f6';
              document.querySelectorAll('.has-lyric li')[i].style.fontSize = '25px';
            }
          }
        }
      }
    }
  },
  computed:{
    ...mapState({
      oldLyric:state => state.info.lyric
    })
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/lyric.scss';
</style>

